package com.bjt.wms.sys.service;

import cn.hutool.core.date.DateUtil;
import com.bjt.common.config.paragetter.BasePageRequest;
import com.bjt.utils.R;
import com.bjt.wms.sys.model.DeliverySheet;
import com.bjt.wms.sys.model.FlowDetail;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

import java.util.List;

/**
 * @author WenbinJi
 * <p>
 * 配货单业务处理
 */
public class DeliverySheetService {

    @Inject
    private MaterialService materialService;

    /**
     * 分页查询
     */
    public R queryList(BasePageRequest<DeliverySheet> basePageRequest, Kv cond) {
        SqlPara sqlPara = Db.getSqlPara("sys.deliverySheet.queryList", cond);

        Page<Record> pageData = Db.paginate(basePageRequest.getPage(), basePageRequest.getLimit(), sqlPara);
        return R.ok().put("data", pageData.getList()).put("count", pageData.getTotalRow());
    }

    /**
     * 完成配货单
     */
    public Ret completeDeliverySheet(int deliverySheetId) {
        DeliverySheet deliverySheet = DeliverySheet.dao.findById(deliverySheetId);
        deliverySheet.setState("已完成");
        deliverySheet.setUpdateTime(DateUtil.date().toString("yyyy-MM-dd hh:mm:ss"));
        return deliverySheet.update() ? Ret.ok() : Ret.fail("msg", "配货单完成失败");
    }

    /**
     * 查询未完成配货单清单
     */

    public List<Record> listDeliverySheet() {
        List<Record> list = Db.find("SELECT  s.*," +
                "(SELECT name from warehouse w where w.id = s.warehouse_id) as warehouse_name," +
                "(SELECT name from employee e where e.id = s.employee_id) as employee_name from delivery_sheet s where s.state='未完成' and s.enable='是'");

        for (int i = 0; i < list.size(); i++) {
            String material_ids = list.get(i).getStr("material_ids");
            List<Record> records = materialService.getMaterialByIds(material_ids);
            list.get(i).set("materials", records);
        }

        return list;
    }

    /**
     * 根据配货单号查询配货单
     */
    public DeliverySheet findByCode(String code)
    {
        return DeliverySheet.dao.findFirst("select * from delivery_sheet where code='"+code+"'");
    }
}
